{% extends "home/base.html" %}
{% block sight %} class="active" {% endblock %}
{% block page_title %} 设施需求权重管理 {% endblock %}

{% block content %}
<div class="col-lg-12">
    <div class="card">
        <div class="card-header">
            <h6 class="card-title">设施需求权重表</h6>
            <div class="card-tools" style="display: flex; gap: 28px; flex-wrap: wrap;">
                <button id="modifyBtn" class="btn btn-sm btn-warning" style="margin: 12px;">
                    <i class="bi bi-pencil"></i> 修改数据
                </button>
                <button id="saveBtn" class="btn btn-sm btn-success" disabled style="margin: 12px;">
                    <i class="bi bi-save"></i> 保存数据
                </button>
                <button id="showDataBtn" class="btn btn-sm btn-info" style="margin: 12px;">
                    <i class="bi bi-display"></i> 计算数据
                </button>
                <button id="exportBtn" class="btn btn-sm btn-primary" style="margin: 12px;">
                    <i class="bi bi-download"></i> 导出CSV
                </button>
                <button id="goToOtherPageBtn" class="btn btn-sm btn-secondary" style="margin: 12px;">
                    <i class="bi bi-box-arrow-right"></i> 跳转页面
                </button>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table id="weightsTable" class="table table-bordered table-hover">
                    <thead class="thead-light">
                        <tr>
                            <th>设施类型</th>
                            <th>青少年</th>
                            <th>青年</th>
                            <th>中年</th>
                            <th>老年</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for row in table_data %}
                        <tr data-id="{{ loop.index }}">
                            <td>{{ row['设施类型'] }}</td>
                            <td class="editable-number">{{ "%.2f"|format(row['青少年']) }}</td>
                            <td class="editable-number">{{ "%.2f"|format(row['青年']) }}</td>
                            <td class="editable-number">{{ "%.2f"|format(row['中年']) }}</td>
                            <td class="editable-number">{{ "%.2f"|format(row['老年']) }}</td>
                            <td>
                                <button class="btn btn-sm btn-danger delete-row" disabled>
                                    <i class="bi bi-trash"></i>
                                </button>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    let isEditMode = false;
    let originalData = [];

    // Store original data
    function storeOriginalData() {
        originalData = [];
        $('#weightsTable tbody tr').each(function() {
            let row = {
                "设施类型": $(this).find('td:eq(0)').text().trim(),
                "青少年": parseFloat($(this).find('td:eq(1)').text().trim()),
                "青年": parseFloat($(this).find('td:eq(2)').text().trim()),
                "中年": parseFloat($(this).find('td:eq(3)').text().trim()),
                "老年": parseFloat($(this).find('td:eq(4)').text().trim())
            };
            originalData.push(row);
        });
    }

    // Initialize original data
    storeOriginalData();

    // Toggle edit mode
    $('#modifyBtn').click(function() {
        isEditMode = !isEditMode;

        if (isEditMode) {
            $(this).removeClass('btn-warning').addClass('btn-danger').html('<i class="bi bi-x"></i> 取消修改');
            $('#saveBtn').prop('disabled', false);

            // Make cells editable
            $('#weightsTable tbody tr').each(function() {
                $(this).find('td:eq(1), td:eq(2), td:eq(3), td:eq(4)').attr('contenteditable', 'true');
                $(this).find('.delete-row').prop('disabled', false);
            });
        } else {
            $(this).removeClass('btn-danger').addClass('btn-warning').html('<i class="bi bi-pencil"></i> 修改数据');
            $('#saveBtn').prop('disabled', true);

            // Revert changes and disable editing
            $('#weightsTable tbody tr').each(function(index) {
                $(this).find('td:eq(1)').text(originalData[index]["青少年"].toFixed(2));
                $(this).find('td:eq(2)').text(originalData[index]["青年"].toFixed(2));
                $(this).find('td:eq(3)').text(originalData[index]["中年"].toFixed(2));
                $(this).find('td:eq(4)').text(originalData[index]["老年"].toFixed(2));

                $(this).find('td').attr('contenteditable', 'false');
                $(this).find('.delete-row').prop('disabled', true);
            });
        }
    });

    // Save data
    $('#saveBtn').click(function() {
        let tableData = [];

        $('#weightsTable tbody tr').each(function() {
            let row = {
                "设施类型": $(this).find('td:eq(0)').text().trim(),
                "青少年": parseFloat($(this).find('td:eq(1)').text().trim()),
                "青年": parseFloat($(this).find('td:eq(2)').text().trim()),
                "中年": parseFloat($(this).find('td:eq(3)').text().trim()),
                "老年": parseFloat($(this).find('td:eq(4)').text().trim())
            };
            tableData.push(row);
        });

        $.ajax({
            url: "{{ url_for('home.hot_sight_back') }}",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                action: 'save',
                table_data: tableData
            }),
            success: function(response) {
                alert(response.message);
                storeOriginalData();
                $('#modifyBtn').click(); // Exit edit mode
            },
            error: function(xhr, status, error) {
                alert('保存失败: ' + error);
            }
        });
    });

    // Export to CSV
    $('#exportBtn').click(function() {
        let tableData = [];

        $('#weightsTable tbody tr').each(function() {
            let row = {
                "设施类型": $(this).find('td:eq(0)').text().trim(),
                "青少年": $(this).find('td:eq(1)').text().trim(),
                "青年": $(this).find('td:eq(2)').text().trim(),
                "中年": $(this).find('td:eq(3)').text().trim(),
                "老年": $(this).find('td:eq(4)').text().trim()
            };
            tableData.push(row);
        });

        $.ajax({
            url: "{{ url_for('home.hot_sight_back') }}",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                action: 'export',
                table_data: tableData
            }),
            success: function(response) {
                // Create a download link
                const url = window.URL.createObjectURL(new Blob([response]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'facility_weights.csv');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            },
            error: function(xhr, status, error) {
                alert('导出失败: ' + error);
            }
        });
    });

    // Validate number inputs
    $(document).on('blur', '.editable-number[contenteditable="true"]', function() {
        let value = $(this).text().trim();
        if (!/^\d*\.?\d*$/.test(value)) {
            alert('请输入有效的数字');
            $(this).text('0.00');
        } else {
            // Format to 2 decimal places
            $(this).text(parseFloat(value).toFixed(2));
        }
    });

    // Delete row
    $(document).on('click', '.delete-row:not(:disabled)', function() {
        if (confirm('确定要删除这行数据吗？')) {
            $(this).closest('tr').remove();
        }
    });

    // 新增展示数据功能
    $('#showDataBtn').click(function() {
        let tableData = [];
        $('#weightsTable tbody tr').each(function() {
            let row = {
                "设施类型": $(this).find('td:eq(0)').text().trim(),
                "青少年": parseFloat($(this).find('td:eq(1)').text().trim()),
                "青年": parseFloat($(this).find('td:eq(2)').text().trim()),
                "中年": parseFloat($(this).find('td:eq(3)').text().trim()),
                "老年": parseFloat($(this).find('td:eq(4)').text().trim())
            };
            tableData.push(row);
        });

        $.ajax({
            url: "{{ url_for('home.hot_sight_back') }}",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                action: 'show_data',
                table_data: tableData
            }),
            success: function(response) {
                alert(response.message);
            },
            error: function(xhr, status, error) {
                alert('计算数据失败: ' + error);
            }
        });
    });

    // 新增跳转页面功能
    $('#goToOtherPageBtn').click(function() {
        window.location.href = "{{ url_for('home.other_page') }}";
    });
});
</script>

<style>
/* 新增按钮样式 */
.card-tools .btn {
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
    line-height: 1.5;
    border-radius: 0.2rem;
    box-shadow: 0 1px 2px rgba(0,0,0,0.1);
    transition: all 0.2s ease-in-out;
}

.card-tools .btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.15);
}

.card-tools .btn:active {
    transform: translateY(0);
    box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

/* 原有样式保持不变 */
.editable-number {
    text-align: right;
}
[contenteditable="true"] {
    padding: 8px;
    border: 1px solid #ddd;
    min-width: 50px;
    background-color: #fff8e1;
}
[contenteditable="true"]:focus {
    outline: 2px solid #4CAF50;
    background-color: #fff8e1;
}
.text-center {
    text-align: center;
}
</style>
{% endblock %}